package com.dq.controller.api.merchant.normal;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dq.cache.J2CacheUtils;
import com.dq.context.event.OrderEvent;
import com.dq.exception.customException.AdminException;
import com.dq.context.listener.ApiInitDataListener;
import com.dq.controller.api.merchant.in.query.OrgPositionQuery;
import com.dq.controller.api.merchant.in.query.ServiceProjectQuery;
import com.dq.controller.api.merchant.in.query.SysRegionQuery;
import com.dq.controller.api.merchant.in.template.AreaTreeBuilder;
import com.dq.controller.in.goods.BossGoodsQuery;
import com.dq.controller.in.base.BaseAdminQuery;
import com.dq.vo.ListDataVo;
import com.dq.vo.Vo;
import com.dq.domain.address.SysRegion;
import com.dq.domain.base.impl.BaseDaoImpl;

import com.dq.domain.orders.UserOrder;
import com.dq.domain.org.Org;
import com.dq.domain.position.OrgPosition;
import com.dq.domain.org.centre.OrgDeptPositionCentre;
import com.dq.domain.sys.section.SysSection;
import com.dq.domain.service.ServiceNullCategory;
import com.dq.domain.service.ServiceProject;
import com.dq.domain.service.ServiceProjectCategory;
import com.dq.domain.service.centre.ServiceProjectCategoryCentre;
import com.dq.domain.sys.user.user.BossUser;
import com.dq.domain.sys.user.user.OrgUser;
import com.dq.domain.sys.user.user.StaffUser;
import com.dq.domain.sys.user.user.WxUser;
import com.dq.service.AllService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author liuhui
 * @date 2019/11/25 0025 15:02:56
 */
@RestController
@RequestMapping("/api/merchant/normal")
@Api(description = "公共查询方法")
public class NormalController extends AllService {


    @GetMapping("/serviceProjectList/{id}")
    @ApiOperation("根据项目类型查询项目")
    public Vo serviceProjectList(@PathVariable Long id)throws AdminException{
        ServiceProjectCategory queryServiceCategory = dao.get(ServiceProjectCategory.class,id);
        if(null==queryServiceCategory){throw new AdminException("服务类别不存在");}
        List<ServiceProjectCategoryCentre> serviceProjectCategoryCentres = serviceProjectCategoryCentreRepository.findByServiceProjectCategory(queryServiceCategory);
        List<Map> serviceProjectListVos = new ArrayList<>();
        serviceProjectCategoryCentres.forEach(serviceProjectCategoryCentre -> {
            Map<String,Object> map = new HashMap<>();
            map.put("id",serviceProjectCategoryCentre.getServiceProject().getId());
            map.put("name",serviceProjectCategoryCentre.getServiceProject().getProjectName());
            serviceProjectListVos.add(map);
        });
        PageInfo pageInfo = new PageInfo(serviceProjectListVos);
        return new Vo(pageInfo);
    }

    @GetMapping("serProCategory/top")
    @ApiOperation("查询全部顶级服务类别")
    public Vo findAllSerProCateList(){
        //TODO 如果空的ServiceNullCategory不能查的话，调用另外一个方法，查询ParentIsNull，后台添加的时候顶级分类父对象设置null
        ServiceNullCategory serviceNullCategory = new ServiceNullCategory();
        List<ServiceProjectCategory> serviceCategoryList = serviceProjectCategoryRepository.findByParentOrderBySortNoAsc(serviceNullCategory);
        List<ServiceProjectCategory.QueryCateVo> querySerCateVos = new ArrayList<>();
        serviceCategoryList.forEach(serviceCategory -> {querySerCateVos.add(serviceCategory.toQueryCateVo());});
        PageInfo pageInfo = new PageInfo(querySerCateVos);
        return new Vo(pageInfo);
}

    @GetMapping("/serProCategory/child/{id}")
    @ApiOperation("根据服务类别查询子服务类别")
    public Vo serProCategoryChild(@PathVariable Long id)throws AdminException{
        ServiceProjectCategory queryServiceCategory = dao.get(ServiceProjectCategory.class,id);
        if(null==queryServiceCategory){throw new AdminException("服务类别不存在");}
        List<ServiceProjectCategory> serviceCategoryList =serviceProjectCategoryRepository.findByParentOrderBySortNoAsc(queryServiceCategory);
        List<ServiceProjectCategory.QueryCateVo> querySerCateVos = new ArrayList<>();
        serviceCategoryList.forEach(serviceCategory -> {querySerCateVos.add(serviceCategory.toQueryCateVo());});
        PageInfo pageInfo = new PageInfo(querySerCateVos);
        return new Vo(pageInfo);
    }

    @GetMapping("/orgPositionList")
    @ApiOperation("查询门店岗位列表")
    public Vo orgPositionList() throws AdminException{
        SysSection org = shiroService.getUser().getSection();
        if(org == null){
            throw new AdminException("请先绑定门店");
        }
        List<OrgDeptPositionCentre> orgDeptPositionCentres =orgDeptPositionRepository.findByDeletedAndOrgOrderByIdDesc(false, (Org) org);
        List<Map> maps = new ArrayList<>();
        orgDeptPositionCentres.forEach(OrgDeptPositionCentre -> {
            if(workRoyaltySetRepository.findByOrgAndOrgPositionAndDeletedFalse(org,OrgDeptPositionCentre.getOrgPosition()).size() > 0){
                Map<String,Object> map = new HashMap<>();
                map.put("name",OrgDeptPositionCentre.getOrgPosition().getPostName());
                map.put("id",OrgDeptPositionCentre.getOrgPosition().getId());
                maps.add(map);
            }
        });
        PageInfo pageInfo = new PageInfo(maps);
        return new Vo(pageInfo);
    }
    @GetMapping("/findStaffByPosition/{id}")
    @ApiOperation("查询门店岗位下的员工")
    public Vo findStaffByPosition(@PathVariable Long id) throws AdminException{
        OrgPosition orgPosition = dao.get(OrgPosition.class,id);
        if(orgPosition == null){
            throw new AdminException("请重新选择岗位");
        }
        List<StaffUser> staffUserList = staffUserRepository.findByOrgPositionAndDeletedFalse(orgPosition);
        List<StaffUser.StaffUserVo> list = new ArrayList<>();
        staffUserList.forEach(staffUser -> {
            list.add(staffUser.toStaffUserVo());
        });
        return new Vo(list);
    }

    @PostMapping("/userOrder/chechout/{id}")
    @ApiOperation("核销订单")
    public Vo userOrderChechOut(@PathVariable Long id)throws AdminException{
        UserOrder userOrder = dao.get(UserOrder.class,id);
        if(null==userOrder){throw new AdminException("订单不存在");}
        userOrder.setStatus(UserOrder.UserOrderStatus.alreadyCheckOut);
        userOrderRepository.save(userOrder);
        //分润
        eventPublisher.publishEvent(new OrderEvent(userOrder));
        //检查用户消费总金额 变动等级
        wxUserLevelService.checkLevel(userOrder);
        return new Vo(HttpStatus.OK);
    }

    @GetMapping("/customer/analysis/time/")
    @ApiOperation("查询用户分析查询条件")
    public Vo customerAnalysisTime(@PathVariable @ApiParam("用户类型") WxUser.CustomerType customerType){
        List<ApiInitDataListener.CustomerTimeQuery> customerTimeQueryList = new ArrayList<>();
        if(customerType.equals(WxUser.CustomerType.active)){
            customerTimeQueryList = (List<ApiInitDataListener.CustomerTimeQuery>)J2CacheUtils.get("CustomerType_Active");
        }else{
            customerTimeQueryList = (List<ApiInitDataListener.CustomerTimeQuery>)J2CacheUtils.get("CustomerType_Silent");
        }
        PageInfo pageInfo = new PageInfo(customerTimeQueryList);
        return new Vo(pageInfo);
    }


    @PostMapping("/bossPositionList")
    @ApiOperation("boos看岗位列表")
    public Vo bossPositionList(@RequestBody OrgPositionQuery orgPositionQuery)throws AdminException{
        orgPositionQuery.format();
        Map<String, Object> query = orgPositionQuery.parseMap();
        if(StringUtils.isNotEmpty(orgPositionQuery.getPostName())){
            query.put("postName"+BaseDaoImpl.likeSqlStr,BaseAdminQuery.likeSql(orgPositionQuery.getPostName()));
            query.remove("postName");
        }
        query.remove("page");
        query.remove("size");
        List<OrgPosition> list = dao.find(dao.query2Hql(OrgPosition.class, query), query);
        List<Map> maps = new ArrayList<>();
        list.forEach(orgPosition -> {
            Map<String,Object> map = new HashMap<>();
            map.put("name",orgPosition.getPostName());
            map.put("id",orgPosition.getId());
            maps.add(map);
        });
        return new Vo(maps);
    }

    @PostMapping("/boosServiceProjectList")
    @ApiOperation("boss看服务项目")
    public Vo boosServiceProjectList(@RequestBody ServiceProjectQuery serviceProjectQuery)throws AdminException{
        Map<String, Object> query = serviceProjectQuery.parseMap();
        if(StringUtils.isNotEmpty(serviceProjectQuery.getName())){
            query.put("projectName"+ BaseDaoImpl.likeSqlStr, BaseAdminQuery.likeSql(serviceProjectQuery.getName()));
            query.remove("name");
        }
        query.remove("page");
        query.remove("size");
        List<ServiceProject> list = dao.find(dao.query2Hql(ServiceProject.class, query), query);
        List<Map> maps = new ArrayList<>();
        list.forEach(serviceProject -> {
            Map<String,Object> map = new HashMap<>();
            map.put("name",serviceProject.getProjectName());
            map.put("id",serviceProject.getId());
            maps.add(map);
        });
        return new Vo(maps);
    }

    @PostMapping("/area/list")
    @ApiOperation("区域列表")
    public Vo areaList(@RequestBody SysRegionQuery sysRegionQuery) throws AdminException{
        Map<String, Object> query = sysRegionQuery.parseMap();
        if(StringUtils.isNotEmpty(sysRegionQuery.getName())){
            query.put("name"+BaseDaoImpl.likeSqlStr,BaseAdminQuery.likeSql(sysRegionQuery.getName()));
            query.remove("name");
        }
        query.remove("page");
        query.remove("size");
        List<SysRegion> list = dao.find(dao.query2Hql(SysRegion.class, query), query);
        Set<SysRegion.Vo> sysRegionVo = new HashSet<>();
        list.forEach(sysRegion -> {
            sysRegionVo.add((SysRegion.Vo) sysRegion.toVO(false));
        });
        List<SysRegion.Vo> voList = AreaTreeBuilder.getRegionTree(sysRegionVo);
        return new Vo(voList);
    }

    @ApiOperation("查询所有岗位为美容导师的人")
    @GetMapping("findAllPosition")
    public Vo findAllPosition() throws AdminException{
        List<BossUser> bossUserList = bossUserRepository.findByOrgPositionPostNameAndStatusAndDeletedFalse("美容导师",BossUser.Status.on);
        JSONArray array = new JSONArray();
        bossUserList.forEach(bossUser -> {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",bossUser.getId());
            jsonObject.put("name",bossUser.getUserRealcName());
            array.add(jsonObject);
        });
        return new Vo(array);
    }

}
